<template>
  <div ref="sentiment" class="sentiment-container">
    <l-map
      :center="mapOption.center"
      :zoom="mapOption.zoom"
      :crs="crs"
      :preferCanvas="true"
      :zoomControl="false"
      :scrollWheelZoom="false"
      @ready="mapReady"
    >
      <l-polygon
        :lat-lngs="polygon.latlngs"
        :color="polygon.color"
        :weight="polygon.weight"
        :options="polygon.options"
      />
      <l-feature-group>
        <l-polyline
          v-for="line in glines"
          :key="line.lng"
          :lat-lngs="line.latlngs"
          :color="line.color"
          :weight="line.weight"
        />
      </l-feature-group>
      <l-geo-json
        :geojson="countrys"
        :options="countryOptions"
        :options-style="countryStyle"
        @ready="countryReady"
      />
      <!-- <l-feature-group>
                <l-polyline
                    v-for="line in flights"
                    :key="line.lng"
                    :lat-lngs="line.latlngs"
                    :color="line.color"
                    :weight="line.weight"
                />
            </l-feature-group> -->
      <!-- <l-geo-json :geojson="flights" :options-style="flightStyle" @ready="flightReady" /> -->

      <l-echart :option="ecOption"></l-echart>
      <l-control-zoom-home :position="'bottomright'" />
      <l-control-expand :position="'bottomleft'">
        <s-map-legend :legend="legend" />
      </l-control-expand>
    </l-map>
    <m-tooltip :show="tip.show">
      <s-map-info :properties="tip.properties"></s-map-info>
    </m-tooltip>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
// import { getLegend } from '../api/map'
import LMap from "../components/LMap/index.vue";
import LGeoJson from "../components/LGeoJson/index.vue";
import LPolyline from "../components/LPolyline/index.vue";
import LPolygon from "../components/LPolygon/index.vue";
// import LMarker from '../components/LMarker/index.vue'
// import LTooltip from "../components/LTooltip/index.vue";
import LEchart from "../components/LEchart/index.vue";
import LFeatureGroup from "../components/LFeatureGroup/index.vue";
import MTooltip from "../components/MTooltip/index.vue";
import LControlZoomHome from "../components/LControlZoomHome/index.vue";
import LControlExpand from "../components/LControlExpand/index.vue";
import { geoEqualEarth } from "d3-geo";
// import { geoKavrayskiy7 } from "d3-geo-projection";
import { linearInterpolation } from "../utils";
// import { generateParabola } from './generateParabola'
// import { bezierSpline } from "@turf/bezier-spline";
// import { init as drawChartsInit } from '../utils/drawCharts'
// import { heatLayer } from '../utils/drawHeatmap'
import SMapInfo from "./components/SMapInfo/index.vue";
import SMapLegend from "./components/SMapLegend/index.vue";
// import MapData from './MapData'
// import { generateHeatmapData, addressPoints } from './generateHeatmap'
import SMapMinxins from "./SMapMinxins";
import proj4leaflet from "../utils/proj4";

export default {
  name: "SentimentMap",
  mixins: [SMapMinxins],
  components: {
    LMap,
    LGeoJson,
    LPolyline,
    LPolygon,
    LFeatureGroup,
    LControlZoomHome,
    LControlExpand,
    LEchart,
    MTooltip,
    SMapInfo,
    SMapLegend,
  },
  computed: {
    ...mapGetters(["name"]),
  },
  data() {
    return {
      mapOption: {
        center: [0, 0],
        zoom: 2,
        // maxBounds: [[-90, -180], [90, 180]],
        worldCopyJump: false,
        // preferCanvas: true,
        attributionControl: false,
      },
      polyline: {
        latlngs: [],
        color: "#999",
        weight: 0.6,
      },
      polygon: {
        latlngs: [],
        color: "#fff",
        weight: 0.6,
        options: {
          render: (ctx, size) => {
            const linearGradient = ctx.createLinearGradient(
              size.x / 2,
              0,
              size.x / 2,
              size.y
            );
            linearGradient.addColorStop(0, "#edf1fd"); // 起点颜色
            linearGradient.addColorStop(1, "#D6DFFF"); // 终点颜色
            return linearGradient;
          },
        },
      },
      glines: [],
      flights: null,
      crs: undefined,
      countrys: null,
      loading: false,
      tip: {
        show: false,
        properties: {},
      },
      nullColor: '#9E9E9E',
      legend: [],
      ecOption: null,
    };
  },
  computed: {
    countryOptions() {
      return {
        onEachFeature: this.onEachFeatureFunction,
      };
    },
    countryStyle() {
      return (feature) => {
        const properties = feature.properties;
        // properties["国家名称"] == "加拿大" &&
        //   console.log(
        //     properties["国家名称"],
        //     properties.hasOwnProperty("fill") ? properties.fill : this.nullColor
        //   );
        return {
          // fillColor: this.getColor(
          //     properties.hasOwnProperty("value")
          //         ? properties.value
          //         : null
          // ),
          fillColor: properties.hasOwnProperty("fill")
            ? properties.fill
            : this.nullColor,
          weight: 1,
          opacity: 1,
          color: "white",
          fillOpacity: 0.7,
        };
      };
    },
    flightStyle() {
      return () => {
        return {
          weight: 1,
          opacity: 1,
          color: "#9C53E5",
        };
      };
    },
    onEachFeatureFunction() {
      // if (!this.enableTooltip) {
      //     return () => {};
      // }

      return (feature, layer) => {
        // layer.bindTooltip(
        //     "<div>name:" +
        //         feature.properties.name +
        //         "</div><div>cc: " +
        //         feature.properties.cc +
        //         "</div>",
        //     { permanent: false, sticky: true }
        // ).openTooltip();
        // layer.bindTooltip(this.createTooltip(feature.properties));
        // .setContent(
        //     this.$createElement(SMapInfo, {
        //         props: { content: "Hello, world!" },
        //     })
        // ); // 使用Vue组件作为内容。
        // layer.on({
        //     mouseover: e => {
        //         /* 高亮逻辑 */
        //         // const mouseEvent = e.originalEvent;
        //         this.tip.show = true
        //         this.tip.properties = feature.properties
        //     },
        //     mouseout: e => {
        //         /* 恢复样式 */
        //         this.tip.show = false
        //     },
        // })
      };
    },
  },
  created() {
    // this.$store.dispatch('map/setClasses')
  },
  mounted() {
    this.setCRS();
  },
  methods: {
    getData() {
      // getInfo().then((response) => {
      //     this.list = response.data.items;
      //     this.listLoading = false;
      // });
      // this.loading = true;
      // const response = await fetch("/countries.geojson");
      // const data = await response.json();
      // this.countrys = data;
      // getLegend()
      //     .then(res => {
      //         const { data } = res
      //         const flights = []
      //         const dataMap = {}
      //         data.YQSJ_TJ.distribute.series[0].data.forEach(d => {
      //             dataMap[d.info.name] = d.value
      //         })
      //         this.countryLayer.eachLayer(layer => {
      //             if (dataMap[layer.feature.properties['国家名称']]) {
      //                 // 更新属性
      //                 Object.assign(layer.feature.properties, {
      //                     value: dataMap[layer.feature.properties['国家名称']],
      //                 })
      //                 // 更新样式
      //                 // this.countryLayer.resetStyle(layer);
      //                 // 设置一下飞线
      //                 if (dataMap[layer.feature.properties['国家名称']] > 130) {
      //                     // flights.push(
      //                     //     bezierSpline(
      //                     //         lineString(
      //                     //             [
      //                     //                 [116, 39.5],
      //                     //                 [
      //                     //                     (116 -
      //                     //                         layer.feature
      //                     //                             .properties[
      //                     //                             "wgs84经度"
      //                     //                         ]) /
      //                     //                         2,
      //                     //                     (39.5 -
      //                     //                         layer.feature
      //                     //                             .properties[
      //                     //                             "wgs84纬度"
      //                     //                         ]) /
      //                     //                         2,
      //                     //                 ],
      //                     //                 [
      //                     //                     layer.feature.properties[
      //                     //                         "wgs84经度"
      //                     //                     ],
      //                     //                     layer.feature.properties[
      //                     //                         "wgs84纬度"
      //                     //                     ],
      //                     //                 ],
      //                     //             ],
      //                     //             {}
      //                     //         )
      //                     //     )
      //                     // );
      //                     // flights.push(
      //                     //     greatCircle(
      //                     //         [116, 39.5],
      //                     //         [
      //                     //             layer.feature.properties[
      //                     //                 "wgs84经度"
      //                     //             ],
      //                     //             layer.feature.properties[
      //                     //                 "wgs84纬度"
      //                     //             ],
      //                     //         ],
      //                     //         {
      //                     //             properties: {
      //                     //                 value: dataMap[
      //                     //                     layer.feature.properties[
      //                     //                         "国家名称"
      //                     //                     ]
      //                     //                 ],
      //                     //             },
      //                     //             npoints: 100,
      //                     //             offset: 100,
      //                     //         }
      //                     //     )
      //                     // );
      //                     flights.push(
      //                         generateParabola(
      //                             [116, 39.5],
      //                             [
      //                                 layer.feature.properties['wgs84经度'],
      //                                 layer.feature.properties['wgs84纬度'],
      //                             ],
      //                             Math.max(39.5, layer.feature.properties['wgs84纬度']) +
      //                                 Math.abs(layer.feature.properties['wgs84经度'] - 116) /
      //                                     5,
      //                             Math.round(
      //                                 (Math.abs(layer.feature.properties['wgs84经度'] - 116) /
      //                                     36) *
      //                                     50
      //                             )
      //                         )
      //                     )
      //                 }
      //             }
      //         })
      //         this.countryLayer.setStyle(this.countryStyle)
      //         this.flights = featureCollection(flights)
      //     })
      //     .finally(() => (this.loading = false))
    },
    async mapReady(map) {
      this.setGraticule();
      // this.setWorld()
      // this.setFlights()

      // this.drawCharts(map);
      // this.drawHeatmapLayer(map);
      map.fitWorld();
      this.map = map;
    },
    countryReady(layer) {
      this.countryLayer = layer;
      // this.getData()
    },
    flightReady(layer) {
      this.flightLayer = layer;
    },
    // update(data) {
    //     this.countrys = data;
    //     this.flights = JSON.parse(JSON.stringify(this.flights));
    // },
    // setWorld() {
    //     this.countrys = MapData
    // },
    setCRS() {
      // const el = this.$refs.sentiment
      // // const width = el.offsetWidth;
      // // const height = el.offsetHeight;
      // const rect = el.getBoundingClientRect()

      // // 宽度和高度
      // const width = rect.width || rect.right - rect.left
      // const height = rect.height || rect.bottom - rect.top

      // // 地图需要固定 2：1 的比例
      // const projection = geoEqualEarth().scale(1).translate([0, 0])
      // const crs = L.Util.extend({}, L.CRS.Simple, {
      //     projection: {
      //         project: function (latlng) {
      //             const point = projection([latlng.lng, latlng.lat])
      //             return new L.Point(point[0], -point[1])
      //         },
      //         unproject: function (point) {
      //             const latlng = projection.invert([point.x, -point.y])

      //             return new L.LatLng(latlng[1] || -1, latlng[0] || -1)
      //         },
      //         // bounds: L.bounds([-180, -90], [180, 90]),
      //         // bounds: L.bounds([-360, -180], [360, 180]),
      //         // bounds: L.bounds([-90, -180], [90, 180]),
      //         // bounds: L.bounds([-180, -90], [180, 90]),
      //     },
      // })
      // this.crs = crs

      this.crs = new proj4leaflet.CRS(
        "ESRI:53035",
        "+proj=eqearth +lon_0=0 +x_0=0 +y_0=0 +R=6371008.7714 +units=m +no_defs +type=crs",
        {
          // eslint-disable-next-line unicorn/numeric-separators-style
          resolutions: [65536, 32768, 16384, 8192, 4096, 2048],
        }
      );
    },
    setGraticule() {
      const latCount = 89;
      const lngLines = linearInterpolation(-180, 180, 19).map((lng) => ({
        lng,
        // latlngs: [[90, lng], [0, lng], [-90, lng]],
        latlngs: [],
        color: "#fff",
        weight: 0.6,
      }));
      const polygonLatlngs = [];
      const latLines = [];
      linearInterpolation(90, -90, latCount).forEach((lat) => {
        polygonLatlngs.unshift([lat, -180]);
        polygonLatlngs.push([lat, 180]);
        lngLines.forEach((line) => {
          line.latlngs.push([lat, line.lng]);
        });
        !(lat % 10) &&
          latLines.push({
            latlngs: [
              [lat, -180],
              [lat, 180],
            ],
            color: "#fff",
            weight: 0.6,
          });
      });
      polygonLatlngs.push([-90, -180]);
      this.polygon.latlngs = polygonLatlngs;
      this.glines = latLines.concat(lngLines);
    },
    // setFlights() {
    // const line = greatCircle([116, 39.5], [0, 51.5], {
    //     properties: {},
    //     // npoints: 100,
    //     // offset: 10,
    // });
    // this.flights = featureCollection([line]);
    // },
    // getColor(value) {
    //     if (!value) return this.$store.state.map.nullColor
    //     const cls = this.$store.state.map.classes.find(
    //         c => c.values[0] < value && value <= c.values[1]
    //     )
    //     return cls ? cls.color : this.$store.state.map.nullColor
    // },
    createTooltip(properties) {
      // const vm = this.$createElement(SMapInfo, {
      //     props: { content: "Hello, world!" },
      // });
      this.tipInfo = properties.name;
      return this.$refs.info.$el;
    },

    // drawCharts(map) {
    //     const demoData = {
    //         fields: ['出生人数', '死亡人数'],
    //         dataset: [
    //             {
    //                 lng: -74,
    //                 lat: 40,
    //                 city: '纽约',
    //                 data: [3927, 1445],
    //             },
    //             {
    //                 lng: 2,
    //                 lat: 48,
    //                 city: '巴黎',
    //                 data: [12664, 2482],
    //             },
    //             {
    //                 lng: 150,
    //                 lat: -33,
    //                 city: '悉尼',
    //                 data: [9929, 6116],
    //             },
    //             {
    //                 lng: 23,
    //                 lat: 73,
    //                 city: '莫斯科',
    //                 data: [1325, 511],
    //             },
    //             {
    //                 lng: 17,
    //                 lat: -22,
    //                 city: '南非',
    //                 data: [6988, 3447],
    //             },
    //         ],
    //     }
    //     const option = { type: 'bar', mode: 'd3' }
    //     const mapCharts = drawChartsInit(demoData, option)
    //     map.addLayer(mapCharts.layer())
    // },
    // drawHeatmapLayer(map) {
    //     const heat = heatLayer(
    //         addressPoints.map(function (p) {
    //             return [p[0], p[1]]
    //         }),
    //         { radius: 25 }
    //     ).addTo(map)
    // },
  },
};
</script>

<style lang="scss" scoped>
.sentiment-container {
  width: 100%;
  height: 100%;
}
</style>
<style>
.echarts-layer-container {
  pointer-events: none;
}

.country {
  background: #dadce3;
}
</style>
